<template>
  <a-form ref="formRef" :model="vdata.currentConfig" layout="vertical" :rules="ifParamsRules">
    <a-row v-if="vdata.mchType === 1" :gutter="16">
      <a-col span="12">
        <a-form-item label="公众号AppID" name="appId">
          <a-input v-model:value.trim="vdata.currentConfig['appId']" placeholder="请输入" @change="changeFun('appId')" />
          <p style="color: rebeccapurple">当使用公众号（JSAPI）支付时需配置该参数</p>
        </a-form-item>
      </a-col>

      <a-divider dashed />

      <a-col span="12">
        <a-form-item label="App支付开放平台AppID" name="openAppId">
          <a-input v-model:value.trim="vdata.currentConfig['openAppId']" placeholder="请输入" @change="changeFun('openAppId')" />
          <p style="color: rebeccapurple">当使用APP支付时需配置该参数(开放平台appId)</p>
        </a-form-item>
      </a-col>

      <a-divider dashed />
      <a-col span="24">
        <a-form-item label="微信支付商户号" name="mchId">
          <a-input v-model:value.trim="vdata.currentConfig['mchId']" placeholder="请输入" @change="changeFun('mchId')" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="微信支付API版本" name="apiVersion">
          <a-radio-group v-model:value="vdata.currentConfig['apiVersion']" defaultValue="V2">
            <a-radio value="V2">V2</a-radio>
            <a-radio value="V3">V3</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="APIv2密钥" name="key">
          <a-input v-model:value.trim="vdata.currentConfig.key" :placeholder=" vdata.encryptionField.key || '请输入APIv2密钥' " @change="changeFun('key')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="APIv3密钥" name="apiV3Key">
          <a-textarea v-model:value="vdata.currentConfig.apiV3Key" :placeholder=" vdata.encryptionField.apiV3Key || '请输入APIv3密钥' " @change="changeFun('apiV3Key')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="序列号" name="serialNo">
          <a-input v-model:value.trim="vdata.currentConfig.serialNo" :placeholder=" vdata.encryptionField.serialNo || '请输入序列号' " @change="changeFun('serialNo')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="API证书(apiclient_cert.p12格式)" name="cert">
          <JeepayUpload v-model:src="vdata.currentConfig['cert']" bizType="cert" fileType="file" accept=".p12" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="证书文件(apiclient_cert.pem格式)" name="apiClientCert">
          <JeepayUpload v-model:src="vdata.currentConfig.apiClientCert" bizType="cert" fileType="file" accept=".pem" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="私钥文件(apiclient_key.pem格式)" name="apiClientKey">
          <JeepayUpload v-model:src="vdata.currentConfig['apiClientKey']" bizType="cert" fileType="file" accept=".pem" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row v-else-if="vdata.mchType === 2" :gutter="16">
      <a-col span="24">
        <a-form-item label="子商户ID" name="subMchId">
          <a-input v-model:value.trim="vdata.currentConfig['subMchId']" placeholder="请输入" @change="changeFun('subMchId')" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="子商户公众号AppId(置空表示使用服务商)" name="subMchAppId">
          <a-input v-model:value.trim="vdata.currentConfig['subMchAppId']" placeholder="请输入" @change="changeFun('subMchAppId')" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="子商户小程序AppId(置空表示使用服务商)" name="subMchAppId">
          <a-input v-model:value.trim="vdata.currentConfig['subMchLiteAppId']" placeholder="请输入" @change="changeFun('subMchLiteAppId')" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="子商户App软件微信开放平台中AppId(使用app支付必填)" name="subMchOpenAppId">
          <a-input v-model:value.trim="vdata.currentConfig['subMchOpenAppId']" placeholder="请输入" @change="changeFun('subMchOpenAppId')" />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>
<script setup lang="ts">
import { ref, reactive, defineExpose } from 'vue'

// 当前的form
const formRef = ref()

const vdata = reactive({
mchType: 1, //商户类型
  // 定义加密的字段
  encryptionField : {
    mchKey: '',
    key: '',
    apiV3Key: '',
    serialNo: '',
  },
  isAdd: true,
  currentConfig: {} as any, // 当前配置项
})
const ifParamsRules=  reactive({
        mchId: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 1 && !value) {
              return Promise.reject(new Error('请输入微信支付商户号'))
            }
            return Promise.resolve()
         } }],
         appId: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 1 && !value) {
              return Promise.reject(new Error('请输入应用AppID'))
            }
            return Promise.resolve()
         } }],
        key: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.currentConfig.apiVersion === 'V2' && !vdata.encryptionField[rule.field] && vdata.mchType === 1 && !value) {
              return Promise.reject(new Error('请输入API密钥'))
            }
            return Promise.resolve()
        } }],
        apiV3Key: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.currentConfig.apiVersion === 'V3' && !vdata.encryptionField[rule.field] && vdata.mchType === 1 && !value) {
              return Promise.reject(new Error('请输入API V3秘钥'))
            }
            return Promise.resolve()
        } }],
        serialNo: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.currentConfig.apiVersion === 'V3' && !vdata.encryptionField[rule.field] && vdata.mchType === 1 && !value) {
              return Promise.reject(new Error('请输入序列号'))
            }
            return Promise.resolve()
        } }],
        apiClientCert: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (vdata.currentConfig['apiVersion'] === 'V3' && !vdata.currentConfig['apiClientCert']) {
              return Promise.reject(new Error('请上传证书文件'))
            }
            return Promise.resolve()
          } }],
        apiClientKey: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.currentConfig.apiVersion === 'V3' && vdata.mchType === 1 && !vdata.currentConfig['apiClientKey']) {
              return Promise.reject(new Error('请上传私钥文件'))
            }
            return Promise.resolve()
        } }],
        subMchId: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 2 && !value) {
              return Promise.reject(new Error('请输入子商户ID'))
            }
            return Promise.resolve()
         } }]
      })


// 对外提供的页面的渲染函数 （ ifDefineArray = 接口的配置定义项数组，  currentConfig = 当前配置项 ）
// 20230918 新增： isProcessStarField = true ( 是否处理 脱敏数据， 默认为 true  )
function pageRender(ifDefineArray, currentConfig, mchType, isProcessStarField = true){
console.log(mchType)

  // 赋值
  vdata.currentConfig = currentConfig
  vdata.mchType = mchType

  // 处理加密数据字段
  if(isProcessStarField){
    Object.keys(vdata.encryptionField).forEach(key => {
      vdata.encryptionField[key] = vdata.currentConfig[key]
      delete vdata.currentConfig[key]
    })
  }

  // 重置form验证
  if (formRef.value !== undefined && formRef.value !== null) {
    formRef.value.resetFields()
  }

}

// 对外提供的获取配置参数函数 （返回JSON类型）
function getConfigParams(){

  return formRef.value.validate().then( () => {
    return convertEncryData()
  })

}

// 转换加密数据
function convertEncryData(){

  // 对象克隆
  let result = Object.assign({}, vdata.currentConfig)
  Object.keys(vdata.encryptionField).forEach(key => {
    // 加密数据 && 空串
    if (!result[key]) {
      delete result[key]
    }
  })
  return result
}

// 消除参数空格
function changeFun(value) {
  if(vdata.currentConfig[value]) {
    vdata.currentConfig[value] = vdata.currentConfig[value].trim()
  }
}

defineExpose({ getConfigParams, pageRender })

</script>
